﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataCom;
using System.Data;
using System.Xml;

namespace XmlDataCommunication
{
    public class XmlPositionLogDataAccess : IPositionLogAccess
    {
        #region IPositionLogAccess Members

        public DataTable GetPositionLogSummary(string from, string to, string line, string shift, string position)
        {
            XmlDocument doc = GeneralFunctions.GetXmlDocument();
            string condition = string.Empty;
            if (line != null) condition += "Line_Code='" + line + "'";
            if (shift != null)
            {
                if (!string.IsNullOrWhiteSpace(condition)) condition += " and ";
                condition += "Shift='" + shift + "'";
            }
            if (condition.Length > 0) condition = "[" + condition + "]";
            XmlNodeList nodes = doc.SelectNodes(string.Format("//R4_PositionLog/Record{0}", condition));

            XmlDocument docResult = new XmlDocument();
            docResult.LoadXml("<Records></Records>");

            foreach (XmlNode positionNode in nodes)
            {
                string logDate = positionNode.SelectSingleNode("./LogDate").InnerText;
                if (DateTime.Parse(logDate) < DateTime.Parse(from) || DateTime.Parse(logDate) > DateTime.Parse(to)) continue;
                string sposition = positionNode.SelectSingleNode("./SPositionID").InnerText;
                string lineCode = positionNode.SelectSingleNode("./Line_Code").InnerText;
                XmlNode linePositionNode = doc.SelectSingleNode(string.Format("//Line_Position/Record[SPositionID='{0}' and Line_Code='{1}']", sposition, lineCode));
                if (linePositionNode == null) continue;
                XmlNode fPositionNode = positionNode.SelectSingleNode("./FPositionID");
                fPositionNode.InnerText += (" " + linePositionNode.SelectSingleNode("./Position").InnerText);
                if (position != null)
                    if (!fPositionNode.InnerText.Contains(position)) continue;
                XmlNode groupedNode = docResult.SelectSingleNode(string.Format(
                    "//Record[Line_Code='{0}' and LogDate='{1}' and Shift='{2}' and LogTime='{3}' and FPositionID='{4}']",
                    positionNode.SelectSingleNode("./Line_Code").InnerText,
                    positionNode.SelectSingleNode("./LogDate").InnerText,
                    positionNode.SelectSingleNode("./Shift").InnerText,
                    positionNode.SelectSingleNode("./LogTime").InnerText,
                    positionNode.SelectSingleNode("./FPositionID").InnerText));
                if (groupedNode == null) docResult.FirstChild.AppendChild(docResult.ImportNode(positionNode, true));
                else
                {
                    XmlNode helpTimeNode = groupedNode.SelectSingleNode("./HelpTime");
                    XmlNode stopTimeNode = groupedNode.SelectSingleNode("./StopTime");
                    XmlNode alarmTimeNode = groupedNode.SelectSingleNode("./AlarmTime");
                    XmlNode phelpTimeNode = positionNode.SelectSingleNode("./HelpTime");
                    XmlNode pstopTimeNode = positionNode.SelectSingleNode("./StopTime");
                    XmlNode palarmTimeNode = positionNode.SelectSingleNode("./AlarmTime");
                    SumNodeValue(helpTimeNode, phelpTimeNode);
                    SumNodeValue(stopTimeNode, pstopTimeNode);
                    SumNodeValue(alarmTimeNode, palarmTimeNode);
                }
            }
            DataTable dt = GeneralFunctions.GetDataTableByXmlNodes(docResult.FirstChild.ChildNodes);
            if (dt.Rows.Count > 0) dt.DefaultView.Sort = "Line_Code asc, LogDate desc, LogTime desc";
            return dt;
        }

        private void SumNodeValue(XmlNode groupedNode, XmlNode node)
        {
            if (string.IsNullOrWhiteSpace(groupedNode.InnerText) && string.IsNullOrWhiteSpace(node.InnerText)) return;
            if (string.IsNullOrWhiteSpace(groupedNode.InnerText) && !string.IsNullOrWhiteSpace(node.InnerText)) groupedNode.InnerText = node.InnerText;
            if (!string.IsNullOrWhiteSpace(groupedNode.InnerText) && string.IsNullOrWhiteSpace(node.InnerText)) return;
            if (!string.IsNullOrWhiteSpace(groupedNode.InnerText) && !string.IsNullOrWhiteSpace(node.InnerText))
                groupedNode.InnerText = (int.Parse(groupedNode.InnerText) + int.Parse(node.InnerText)).ToString();
        }

        public DataTable GetPositionLog(string from, string to, string line, string shift, string position)
        {
            XmlDocument doc = GeneralFunctions.GetXmlDocument();
            string condition = string.Empty;
            if (line != null) condition += "Line_Code='" + line + "'";
            if (shift != null)
            {
                if (!string.IsNullOrWhiteSpace(condition)) condition += " and ";
                condition += "Shift='" + shift + "'";
            }
            if (condition.Length > 0) condition = "[" + condition + "]";
            XmlNodeList nodes = doc.SelectNodes(string.Format("//R4_PositionLog/Record{0}", condition));

            XmlDocument docResult = new XmlDocument();
            docResult.LoadXml("<Records></Records>");

            foreach (XmlNode positionNode in nodes)
            {
                string logDate = positionNode.SelectSingleNode("./LogDate").InnerText;
                if (DateTime.Parse(logDate) < DateTime.Parse(from) || DateTime.Parse(logDate) > DateTime.Parse(to)) continue;
                string sposition = positionNode.SelectSingleNode("./SPositionID").InnerText;
                string lineCode = positionNode.SelectSingleNode("./Line_Code").InnerText;
                XmlNode linePositionNode = doc.SelectSingleNode(string.Format("//Line_Position/Record[SPositionID='{0}' and Line_Code='{1}']", sposition, lineCode));
                if (linePositionNode == null) continue;
                XmlNode fPositionNode = positionNode.SelectSingleNode("./FPositionID");
                fPositionNode.InnerText += (" " + linePositionNode.SelectSingleNode("./Position").InnerText);
                if (position != null)
                    if (!fPositionNode.InnerText.Contains(position)) continue;
                docResult.FirstChild.AppendChild(docResult.ImportNode(positionNode, true));
            }
            DataTable dt = GeneralFunctions.GetDataTableByXmlNodes(docResult.FirstChild.ChildNodes);
            if (dt.Rows.Count > 0) dt.DefaultView.Sort = "Line_Code asc, LogDate desc, LogTime desc";
            return dt;
        }

        /// <summary>
        /// Update Position Log By Key
        /// </summary>
        /// <param name="lineCode"></param>
        /// <param name="logDate"></param>
        /// <param name="shift"></param>
        /// <param name="logTime"></param>
        /// <param name="type"></param>
        /// <param name="sPositionID"></param>
        /// <param name="fPositionID"></param>
        /// <param name="stopTime"></param>
        /// <param name="helpTime"></param>
        /// <param name="alarmTime"></param>
        public void UpdatePositionLogByKey(string lineCode,
                                           string logDate,
                                           string shift,
                                           string logTime,
                                           string type,
                                           string sPositionID,
                                           string fPositionID,
                                           string stopTime,
                                           string helpTime,
                                           string alarmTime)
        {
            XmlDocument doc = GeneralFunctions.GetXmlDocument();
            XmlNode node = doc.SelectSingleNode("//R4_PositionLog/Record[Line_Code='" + lineCode + "' and LogDate='" + logDate + "' and LogTime='" + logTime + "' and Type='" + type + "' and SPositionID='" + sPositionID + "']");

            if (node == null)
            {
                List<string> columnNames = new List<string>()
                {
                    "Line_Code","LogDate","Shift","LogTime","Type","SPositionID","FPositionID","StopTime","HelpTime","AlarmTime"
                };
                node = GeneralFunctions.CreateRecordInTable(doc, "R4_PositionLog", columnNames);
                node.SelectSingleNode("./Line_Code").InnerText = lineCode;
                node.SelectSingleNode("./LogDate").InnerText = logDate;
                node.SelectSingleNode("./LogTime").InnerText = logTime;
                node.SelectSingleNode("./Type").InnerText = type;
                node.SelectSingleNode("./SPositionID").InnerText = sPositionID;
            }

            node.SelectSingleNode("./Shift").InnerText = shift;
            node.SelectSingleNode("./FPositionID").InnerText = fPositionID;
            node.SelectSingleNode("./StopTime").InnerText = stopTime;
            node.SelectSingleNode("./HelpTime").InnerText = helpTime;
            node.SelectSingleNode("./AlarmTime").InnerText = alarmTime;

            GeneralFunctions.SaveXmlDocument(doc);
        }

        /// <summary>
        /// Update Position Log Temp By Key
        /// </summary>
        /// <param name="lineCode"></param>
        /// <param name="logDate"></param>
        /// <param name="shift"></param>
        /// <param name="logTime"></param>
        /// <param name="type"></param>
        /// <param name="sPositionID"></param>
        /// <param name="fPositionID"></param>
        /// <param name="stopTime"></param>
        /// <param name="helpTime"></param>
        /// <param name="alarmTime"></param>
        public void UpdatePositionLogTempByKey(string lineCode,
                                               string logDate,
                                               string shift,
                                               string logTime,
                                               string type,
                                               string sPositionID,
                                               string fPositionID,
                                               string stopTime,
                                               string helpTime,
                                               string alarmTime)
        {
            XmlDocument doc = GeneralFunctions.GetXmlDocument();
            XmlNode node = doc.SelectSingleNode("//PositionLog_Tmp/Record[Line_Code='" + lineCode + "' and LogDate='" + logDate + "' and Shift='" + shift + "' and Type='" + type + "' and SPositionID='" + sPositionID + "']");

            if (node == null)
            {
                List<string> columnNames = new List<string>()
                {
                    "Line_Code","LogDate","Shift","LogTime","Type","SPositionID","FPositionID","StopTime","HelpTime","AlarmTime"
                };
                node = GeneralFunctions.CreateRecordInTable(doc, "PositionLog_Tmp", columnNames);
                node.SelectSingleNode("./Line_Code").InnerText = lineCode;
                node.SelectSingleNode("./LogDate").InnerText = logDate;
                node.SelectSingleNode("./Shift").InnerText = shift;
                node.SelectSingleNode("./Type").InnerText = type;
                node.SelectSingleNode("./SPositionID").InnerText = sPositionID;
            }

            node.SelectSingleNode("./LogTime").InnerText = logTime;
            node.SelectSingleNode("./FPositionID").InnerText = fPositionID;
            node.SelectSingleNode("./StopTime").InnerText = stopTime;
            node.SelectSingleNode("./HelpTime").InnerText = helpTime;
            node.SelectSingleNode("./AlarmTime").InnerText = alarmTime;

            GeneralFunctions.SaveXmlDocument(doc);
        }

        #endregion
    }
}
